/**
 * Created by yangfan on 2016/10/24.
 */
define(["require",
    'config/appregister',
    "i18n",
    "config/uploadFile",
    "business/services/httpServices",
    "business/library/services/httpServices",
    "business/personMine/services/httpServices",
    "business/services/constant",
    "business/services/utils",
    "business/home/directives/editorDirective",
    "business/home/directives/uploadDirective"
],function(require,app,i18n,uploadFile,httpService,libHttpServices,personHttpServices,constant,utils){
    app.controller('uploadModifiCtrl',function($scope,$state,$stateParams,$q) {
    	//标签
    	$scope.tags2 = [];
        $scope.controlLength = function(str){
            var l = str.length;
            var blen = 0;
            for(var i=0; i<l; i++) {
                if (str.charCodeAt(i) > 255) {
                    blen ++;
                }
                blen ++;
            }
            if(blen == 32){
                var maxLength = $scope.tagsWork.length;
            }
            if(blen > 32){
                $scope.tagsWork.length = maxLength;
            }
        }
        $scope.saveTagsname=function(a){
            if(a == ''){
                return;
            }
        	if($scope.tags2.length == 6){
        		alert('最多只能添加六个关键词哦，亲');
        		return;
        	}
            if($scope.tags2.indexOf(a) != -1){
                alert("关键词不能相同哦")
            }else{
                $scope.tags2.push(a);
                $scope.tagsWork = '';
            }
        }
        $scope.deleteInput=function($index){
            $scope.tags2.splice($index,1);
        }
    	
    	
            var deffer = $q.defer() ;
            $scope.isDetailPage = false;
            $scope.isMainpage = true;
            $scope.showFillInfo = true;
            $scope.i18n = i18n;
            $scope.mainData = {
                logoSrc:"them/images/gcj_big_logo.png"
            };
            $scope.showTemplate = {
                isSelectFile:false,
                isUploadFile:true,
                showFillLeftL:false
            };
            $scope.fillInfo = "您已成功上传1份文件 ， 失败0份";
            $scope.successNoticeInfo = "您已成功上传1个文件，审核通过后，将获得 5 积分";
            $scope.uploadFileName = "";
            $scope.uploadNoticeInfo = "";
            $scope.listParams ={
                tcId:"",
                id:""
            };
            //文件上传参数
            $scope.uploadInfo  = {
                typeId:"",
                tcId:"",
                scId:"",
                name:"",
                size:"",
                tagsId:"",
                price:"",
                path:"",
                introduction:"",

                //dcIds 为一个纯id 数组 ，取的时候 需要分离
                dcIds:"",
                fileId:""
            };

            if(!angular.isUndefined($stateParams.tcId)&&!angular.isUndefined($stateParams.id)){
                $scope.uploadInfo.tcId = $stateParams.tcId ;
                $scope.uploadInfo.fileId = $stateParams.id;
                getFile().then(function(data){
                    if($stateParams.tcId == 3){
                        $scope.uploadInfo.scId = data.file.scId ;
                        $scope.uploadInfo.dcIds = data.file.dcId;
                    }else{
                        $scope.uploadInfo.scId = data.secCategory.scId ;
                        $scope.uploadInfo.dcIds = utils.getIdsArray( data.detailCategory,'dcId');
                    }
                    getSecCategory($scope.uploadInfo.tcId)
                })
            }else {
                return
            }

            function getFile(){
                var req = {
                    type:"GET",
                    uri:"get",
                    data:{}
                };
                if($stateParams.tcId == 3){
                    req.data.thesisId = $scope.uploadInfo.fileId;
                    personHttpServices.libServices(req).success(function(response){
                        $scope.$apply(function(){
                            $scope.file = response.data.file;
                            for(var i = 0;i < response.data.file.labelList.length;i++){
                                $scope.tags2.push(response.data.file.labelList[i].labelName)
                            }
                            deffer.resolve(response.data);
							/*for(var i = 0;i<response.data.file.labelList.length;i++){
								$scope.tags2.push(response.data.file.labelList[i].tcName);
							}*/
                        })
                    }).error(function(response){})
                }else if($scope.uploadInfo.tcId ==1 ||$scope.uploadInfo.tcId ==2){
                    req.data.fileId = $scope.uploadInfo.fileId;
                    personHttpServices.dataServices(req).success(function(response){
                            $scope.$apply(function(){
                                if(response.data.file.scId == 16){
                                    $scope.major1 = '专业';
                                    $scope.major2 = '内容';
                                    $scope.major3 = '项目模式';
                                }else if(response.data.file.scId == 15){
                                    $scope.major1 = '国家';
                                    $scope.major2 = '专业';
                                    $scope.major3 = '种类';
                                }else if(response.data.file.scId == 17){
                                    $scope.major1 = '经济环境';
                                    $scope.major2 = '法律法规';
                                    $scope.major3 = '宗教文化';
                                    $scope.major4 = '合同管理';
                                }
                                $scope.file = response.data.file;
                                for(var i = 0;i < response.data.file.tagList.length;i++){
                                    $scope.tags2.push(response.data.file.tagList[i].name)
                                }
                                deffer.resolve(response.data.category);
                            })
                    }).error(function(response){})
                }
                return deffer.promise;
            };


            //多文件上传时用于判断文件类型
            $scope.currentFileType = "";
            $scope.goTo = function(state){
                if(state == 'eng.uploadSelectFile'){
                    $state.transitionTo(state, {}, {
                        reload: true, inherit: false, notify: true
                    });
                }else{
                    $state.go(state);
                }

            };


            //隐藏二级目录
            $scope.isShowSec = true;

            //单文件时 上传文件
            function uploadInfo (){
                var arr = [],dcId;
                if($scope.tags2 == []){
                    return;
                }
                if($scope.uploadInfo.tcId ==2){
                    if($scope.interDcIds.major){
                        arr.push($scope.interDcIds.major)
                    }
                    if($scope.interDcIds.content){
                        arr.push($scope.interDcIds.content)
                    }
                    if($scope.interDcIds.projectPattern){
                        arr.push($scope.interDcIds.projectPattern)
                    }
                    if($scope.interDcIds.manage){
                        arr.push($scope.interDcIds.manage)
                    }
                    dcId = arr.join(",");
                }else{
                    dcId =$scope.uploadInfo.dcIds;
                };
                var req = {
                    type:"POST",
                    uri:"update",
                    data:{
                        typeId:$scope.file.typeId,
                        tcId:$scope.uploadInfo.tcId,
                        scId:$scope.uploadInfo.scId,
                        name:$scope.file.name,
                        size:$scope.file.size,
                        //tagIds:6,
                        price:$scope.file.price,
                        path:$scope.file.path,
                        introduction:$scope.file.introduction
                    }
                };
                if($stateParams.tcId ==3){
                    req.data.dcId = $scope.uploadInfo.dcIds;
                }
                else {
                    var arr = [],dcId;
                    if($stateParams.tcId ==2){
                        if($scope.interDcIds.major){
                            arr.push($scope.interDcIds.major)
                        }
                        if($scope.interDcIds.content){
                            arr.push($scope.interDcIds.content)
                        }
                        if($scope.interDcIds.projectPattern){
                            arr.push($scope.interDcIds.projectPattern)
                        }
                        if($scope.interDcIds.manage){
                            arr.push($scope.interDcIds.manage)
                        }
                        req.data.dcIds = arr.join(",");
                    }else{
                        req.data.dcIds =$scope.uploadInfo.dcIds;
                    };
                }

                // 获取标签id
                    var requestion = {
                        type:"POST",
                        uri:"add",
                    };
                if($stateParams.tcId ==3){
                    requestion.data = {
                        labels:$scope.tags2.join(',')
                    };
                    libHttpServices.tagServices(requestion).success(function(response){
                        $scope.uploadInfo.labelIds = response.data.join(",");
                            req.data.thesisId = $scope.file.thesisId ;
                            req.data.labelIds = $scope.uploadInfo.labelIds ;
                            addFileByPostByLib(req)
                    }).error(function(){
                    })
                }else{
                    requestion.data = {
                        tags:$scope.tags2.join(',')
                    };
                    httpService.tagServices(requestion).success(function(response){
                        $scope.uploadInfo.labelIds = response.data.join(",");
                            req.data.fileId = $scope.file.fileId ;
                            req.data.tagIds = $scope.uploadInfo.labelIds ;
                            addFileByPost(req)

                    }).error(function(){
                    })
                }



            }
            //获取一二级资料目录
            function getTopCategory(){
                var requestion = {
                    type: "GET",
                    param: "getTopCategory"
                };
                if($stateParams.tcId ==1 ||$stateParams.tcId ==2 ){
                    httpService.getTopCategory(requestion).success(function (response) {
                        if (response.msg !== "success") {
                            return
                        }
                        //  得到 一级分类 分类名
                        $scope.engClassify = response.data;
                        console.log("一级分类");
                        console.log($scope.engClassify);
                    }).error(function () {
                        console.log("请求失败！");
                    });
                }
                if($stateParams.tcId ==3){
                    var reqlib = {
                        type:"GET",
                        uri:"getTopCategory"
                    };
                    libHttpServices.getTopCategory(reqlib).success(function (response) {
                        if (response.msg !== "success") {
                            return
                        }
                        //  得到 一级分类 分类名
                        $scope.engClassify = response.data;
                        console.log("一级分类");
                        console.log($scope.engClassify);
                    }).error(function () {
                        console.log("请求失败！");
                    });
                }

            }

            //获取二级目录资料分类
            function getSecCategory(tcId){
                var req2 = {
                    type: "GET",
                    tcId: tcId,
                    param: 'getSecondaryCategory',
                };
                if($stateParams.tcId ==1 ||$stateParams.tcId ==2 ){
                    httpService.getSecondCategory(req2).success(function (response) {
                        if (response.data) {
                            $scope.$apply(function(){
                                $scope.secCate = response.data;
                                getDetailCategory($scope.uploadInfo.scId);
                            })
                        }
                    });
                }
                if($stateParams.tcId ==3){
                    var req3 = {
                        type: "GET",
                        uri:"getSecondaryCategory",
                        data:{
                            tcId :$stateParams.tcId
                        }
                    };
                    libHttpServices.getSecondaryCategory(req3).success(function (response) {
                        if (response.data) {
                            $scope.$apply(function(){
                                $scope.secCate = response.data;
                                getDetailCategory($scope.uploadInfo.scId);
                            })
                        }
                    });
                }

            }

            //获取三级目录资料分类
            function getDetailCategory(scId){
                if(!$scope.uploadInfo.tcId) return;
                var req3 = {
                    type: "GET",
                    data: {
                        scId: scId,
                        tcId: $scope.uploadInfo.tcId
                    },
                    param: 'getDetailCategory'
                };
                if($stateParams.tcId ==1 ||$stateParams.tcId ==2 ){
                    httpService.getDetailCategory(req3).success(function (response) {
                        if(response.data){
                            $scope.$apply(function(){

                                // 根据国际 国内不同 显示两种不同的select 选择框
                                if($scope.uploadInfo.tcId == 1){
                                    $scope.isShowNationDec = true;
                                }else if($scope.uploadInfo.tcId ==2){
                                    $scope.isShowInterDec = true;
                                }
                                $scope.curDetail = response.data;
                                $scope.isShowInterDec = true ;
                            })
                        }
                    }).error(function (response) {
                    })
                }
                if($stateParams.tcId == 3){
                    var req4 = {
                        type: "GET",
                        data: {
                            scId: scId,
                            tcId: $scope.uploadInfo.tcId
                        },
                        uri: 'getDetailCategory'
                    };
                    libHttpServices.getDetailCategory(req4).success(function (response) {
                        if(response.data){
                            $scope.$apply(function(){
                                $scope.curDetail = response.data
                            })
                        }
                    }).error(function (response) {
                    })
                }

            }

            //点击确认 上传文件信息
            function addFileByPost(req){
                httpService.addFile(req).success(function(response){

                    $scope.$apply(function(){
                        $scope.showFillInfo = false;
                    });
                }).error(function(){
                    $scope.uploadNoticeInfo = "文件上传失败";
                })
            }

            //点击确认 上传论文文件信息
            function addFileByPostByLib(req){
                libHttpServices.addFile(req).success(function(response){

                    $scope.$apply(function(){
                        $scope.showFillInfo = false;
                    });
                }).error(function(){
                    $scope.uploadNoticeInfo = "文件上传失败";
                })
            }


            //初始化一级目录分类
            getTopCategory();

            // TopCategory options  change事件
            var backgroundObj = {
                background:"#00A4FF",
                color:"#fff"
            };
            $scope.changeTcOptions = function(item,index){

                if(item.tcId == 1){
                    $scope.isShowSec = true;
                    $scope.isShowNationDec = false;
                    $scope.isShowInterDec = false;
                }else{
                    $scope.isShowSec = false;
                    $scope.isShowInterDec = true;
                }
                $scope.uploadInfo.tcId = item.tcId;
                $scope.uploadInfo.scId = [];
                $scope.interDcIds= {
                    major:"",
                    content:"",
                    projectPattern:"",
                    manage:""
                };
                getSecCategory(item.tcId)  ;
            };

            // SecCategory options  change事件
            $scope.changeScOptions = function(item,index){

                $scope.isCheckForSc = [];
                $scope.isCheckForDc = [];
                $scope.isCheckForSc = backgroundObj ;
                if(item.scName == "项目管理"){
                    $scope.major1 = '专业';
                    $scope.major2 = '内容';
                    $scope.major3 = '项目模式';
                }else if(item.scName == "技术规范"){
                    $scope.major1 = '国家';
                    $scope.major2 = '专业';
                    $scope.major3 = '种类';
                }else if(item.scName == "国际商务"){
                    $scope.major1 = '经济环境';
                    $scope.major2 = '法律法规';
                    $scope.major3 = '宗教文化';
                    $scope.major4 = '合同管理';
                }
                if(!item)return;
                if(item.tcId ==1){
                    $scope.isShowNationDec = true;
                }else{
                    $scope.isShowInterDec = true;
                    if(typeof index == 'number'){
                       // $scope.showInterDecCate = [];
                        //$scope.showInterDecCate[index] = true;
                    }
                }
                $scope.interDcIds= {
                    major:"",
                    content:"",
                    projectPattern:"",
                    manage:""
                };
                if(item.tcId == 2){
                    $scope.uploadInfo.dcIds = [];
                }else{
                    $scope.uploadInfo.dcIds = "";
                }
                $scope.uploadInfo.scId = item.scId;
                getDetailCategory(item.scId);
            };
            $scope.selectedStyle = backgroundObj ;

            //国内时， 三级分类change 事件
            $scope.changeDcOptions = function(item ,index){
                $scope.uploadInfo.dcIds = [];
                $scope.uploadInfo.dcIds.push( item.dcId);
            };
            //select 复选框设置
            var expanded = false;
            $scope.showCheckboxes = function(){
                var checkboxes = document.getElementById("checkboxes");
                if (!expanded) {
                    checkboxes.style.display = "block";
                    expanded = true;
                } else {
                    checkboxes.style.display = "none";
                    expanded = false;
                }
            };

            $scope.isCurentDc = function(arr,curValue){
                if($stateParams.tcId == 3){
                    return  arr == curValue
                }else {
                    return  arr.some(function(item){
                        return  item == curValue
                    })
                }

            }
            // 获取国际情形下 三级分类复选 选中的id数组
            $scope.interDc = [];
            $scope.interDcIds= {
                major:"",
                content:"",
                projectPattern:"",
                manage:""
            };
            $scope.changeCheckbox = function(event,item){
                if(!item){
                    return ;
                }

                //如果选中 则插入
                if(event.target.checked){
                    if($scope.interDc.indexOf(item.dcId)==-1){
                        $scope.interDc.push(item.dcId);
                    }
                }

                // 如果取消选中 则从数组中移除
                if(!event.target.checked){
                    var index = $scope.interDc.indexOf(item.dcId);
                    if(index!=-1){
                        $scope.interDc.splice(index, 1);
                    }
                }
                $scope.uploadInfo.dcIds =  $scope.interDc;
            };

            $scope.addFile = function(){
                uploadInfo();
            };

            $scope.editFileInfo = function(){
                $scope.showTemplate.showFillLeftL = !$scope.showTemplate.showFillLeftL;
                if($scope.editSrc == $scope.src.V){
                    $scope.editSrc = $scope.src.A;
                }else{
                    $scope.editSrc = $scope.src.V;
                }
            };
            $scope.src = {
                V:"them/images/V_logo.png",
                A:"them/images/A_logo.png"
            };
            $scope.editSrc = $scope.src.V;
            $scope.upload = {
                url:constant.config.BASEURL_UPLOAD,
                api:constant.config.CONSTANT_UPLOADER,
                path:"",
                file:"",
                onchange:function(){
                    //$scope.$apply(function(){
                    //    $scope.showTemplate.isSelectFile = true;
                    //    $scope.showTemplate.isUploadFile = false;
                    //});
                }
            };

            $scope.$on("uploadSuccess",function(data){
                $scope.$apply(function(){
                    $scope.showTemplate.isSelectFile = true;
                    $scope.showTemplate.isUploadFile = false;
                })
            })
        }
    )
});

